<template>
  <el-dialog :title="dialogForm.id? '编辑分类':'添加分类'" :visible="showDialog" @close="cancel" @opened="show">
    <el-form ref="form" :model="dialogForm" :rules="rules" label-width="80px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="dialogForm.title" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <!-- resize:none去除右下角 -->
        <el-input
          v-model="dialogForm.desc"
          type="textarea"
          :rows="2"
        />
      </el-form-item>
      <el-form-item label="封面" prop="image">
        <upload ref="imgList" />
        <el-input v-model="dialogForm.image" type="text" placeholder="强制设置图片跳过上传" />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button type="primary" size="small" @click="confirm">确 定</el-button>
      <el-button size="small" @click="cancel">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
// 接口
import { addClassiFication, editclassiFication } from '@/api/classification'

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogForm: {
        title: '',
        desc: ''
      },
      rules: {
        title: [{ required: true, message: '该项不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '该项不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
  },
  methods: {
    // 打开弹框动画关闭触发
    show() {
      // 编辑时显示弹框图片
      const imgUrl = this.dialogForm.image
      console.log(imgUrl)
      if (imgUrl) {
        this.$refs.imgList.fileList = [
          { url: imgUrl }
        ]
      }
    },
    // 确定
    async confirm() {
      const fileList = this.$refs.imgList.fileList
      await this.$refs.form.validate()
      if (fileList[0] && fileList[0].status !== 'success') {
        this.$message.error('请等待图片上传完毕')
      }
      const formData = {
        ...this.dialogForm,
        image: fileList ? fileList[0].url : ''
      }
      if (this.dialogForm.id) {
        await editclassiFication(formData)
        this.$message.success('修改成功')
      } else {
        await addClassiFication(formData)
        this.$message.success('添加成功')
      }
      this.$emit('reload')
      this.$emit('close')
    },
    // 取消
    cancel() {
      this.$emit('close')
      this.$refs.form.clearValidate()
      this.dialogForm = {}
      this.$refs.imgList.fileList = []
    }
  }
}
</script>

<style lang="scss"  scoped>
::v-deep .el-textarea__inner{
    resize: none;
    width: 100%;
    height: 100px;
}
.disable {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
